<?php
namespace app\common\model;

use think\Model;

class DataUserWxapp extends Model
{
	protected $table = 'data_user_wxapp';
	// 设置主键字段
	protected $pk = 'user_id';

	// 自动写入时间戳字段
	protected $autoWriteTimestamp = true;

	// 小程序信息 
	protected $appid = "wx864dd1d0ceff3dc7";
	protected $secret = "89b739c64287d0ee105656425d99c291";

	static function getWxUserOpenid ($code = "") {
		if ($code == "") return "error";
		$curl = curl_init();
		// 构建url地址
		$url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . env('wxapp.appid') . "&secret=" . env('wxapp.appsecret') . "&js_code=" . $code . "&grant_type=authorization_code";
		curl_setopt($curl, CURLOPT_URL, $url);
		// 设置是否输出 header
		curl_setopt($curl, CURLOPT_HEADER, false);
		// 设置是否输出结果
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		// 设置是否检查服务器端的证书
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		// 接收返回数据
		$result = curl_exec($curl);
		// 关闭 curl 会话
		curl_close($curl);
		// 返回
		if (!strstr($result,"openid")) {
			abort(202, "获取OPENID失败~");
		}
		// $s = str2arr($result);
		return str2arr($result)['openid'];
	}

}
